package com.tuyrt.`as`.proj.main.biz.detail

import android.content.Context
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.BackgroundColorSpan
import android.text.style.ForegroundColorSpan
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.tuyrt.`as`.proj.common.ui.view.loadUrl
import com.tuyrt.`as`.proj.main.R
import com.tuyrt.`as`.proj.main.fragment.home.GoodsItem
import com.tuyrt.`as`.proj.main.model.DetailModel
import com.tuyrt.`as`.proj.main.model.Shop
import com.tuyrt.`as`.proj.main.model.GoodsModel
import com.tuyrt.hi.ui.item.HiAdapter
import com.tuyrt.hi.ui.item.HiDataItem
import com.tuyrt.hi.ui.item.HiViewHolder
import kotlinx.android.synthetic.main.layout_detail_item_shop.*
import kotlinx.android.synthetic.main.layout_detail_item_shop_goods_item.*

/**
 *  店铺模块= 基础信息+ 关联商品
 */
class ShopItem(private val detailModel: DetailModel) : HiDataItem<DetailModel, HiViewHolder>() {
    private val SHOP_GOOD_ITEM_SPAN_COUNT: Int = 3

    override fun onBindData(holder: HiViewHolder, position: Int) {
        val context = holder.itemView.context ?: return
        val shop: Shop? = detailModel.shop
        shop?.let {
            val tabContainer = holder.tag_container
            tabContainer.visibility = View.VISIBLE

            holder.shop_logo.loadUrl(it.logo)
            holder.shop_title.text = it.name
            holder.shop_desc.text = String.format(context.getString(R.string.shop_desc), it.goodsNum, it.completedNum)

            val evaluation = shop.evaluation
            evaluation?.let {
                val serviceTags = it.split(" ")
                var index = 0
                for (tagIndex in 0 until serviceTags.size / 2) { // 6 3-> in 0 until 3

                    val tagView: TextView = if (tagIndex < tabContainer.childCount) {
                        tabContainer.getChildAt(tagIndex) as TextView
                    } else {
                        val tagView = TextView(context)
                        val params =
                            LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT)
                        params.weight = 1f
                        tagView.layoutParams = params
                        tagView.gravity = Gravity.CENTER
                        tagView.textSize = 14f
                        tagView.setTextColor(ContextCompat.getColor(context, R.color.color_666))
                        tabContainer.addView(tagView)
                        tagView
                    }

                    val serviceName = if (index >= serviceTags.size) continue else serviceTags[index]
                    val serviceTag = serviceTags[index + 1]
                    index += 2

                    val spanTag = spanServiceTag(context, serviceName, serviceTag)
                    tagView.text = spanTag
                }
            }
        }

        val flowGoods = detailModel.flowGoods
        flowGoods?.let {
            val flowRecyclerView = holder.flow_recycler_view
            flowRecyclerView.visibility = View.VISIBLE

            // 因为复用问题：判断null添加 layoutManager、adapter
            if (flowRecyclerView.layoutManager == null) {
                flowRecyclerView.layoutManager = GridLayoutManager(context, SHOP_GOOD_ITEM_SPAN_COUNT)
            }

            if (flowRecyclerView.adapter == null) {
                flowRecyclerView.adapter = HiAdapter(context)
            }

            val dataItems = mutableListOf<GoodsItem>()
            it.forEach {
                dataItems.add(ShopGoodsItem(it))
            }

            val adapter = flowRecyclerView.adapter as HiAdapter
            adapter.clearItems()
            adapter.addItems(dataItems, true)
        }
    }

    private inner class ShopGoodsItem(goodsModel: GoodsModel) : GoodsItem(goodsModel, false) {

        override fun getItemLayoutRes(): Int {
            return R.layout.layout_detail_item_shop_goods_item
        }

        override fun onViewAttachedToWindow(holder: HiViewHolder) {
            super.onViewAttachedToWindow(holder)
            val viewParent = holder.itemView.parent as ViewGroup
            val availableWidth = viewParent.measuredWidth - viewParent.paddingLeft - viewParent.paddingRight
            val itemWidth = availableWidth / SHOP_GOOD_ITEM_SPAN_COUNT

            val itemImage = holder.item_image
            val params = itemImage.layoutParams
            params.width = itemWidth
            params.height = itemWidth
            itemImage.layoutParams = params
        }
    }

    private fun spanServiceTag(context: Context, serviceName: String, serviceTag: String): CharSequence {
        val ss = SpannableString(serviceTag)
        val ssb = SpannableStringBuilder()

        ss.setSpan(
            ForegroundColorSpan(ContextCompat.getColor(context, R.color.color_c61)),
            0,
            ss.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        ss.setSpan(
            BackgroundColorSpan(ContextCompat.getColor(context, R.color.color_f8e)),
            0,
            ss.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        ssb.append(serviceName)
        ssb.append(ss)
        return ssb
    }


    override fun getItemLayoutRes(): Int {
        return R.layout.layout_detail_item_shop
    }
}